<?php

namespace app\admin\controller\finance;

use addons\shopro\model\UserWalletLog;
use app\admin\model\shopro\Agentstore;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;


/**
 * 订单按日汇总
 *
 * @icon fa fa-circle-o
 */
class Orderdayrpt extends Backend
{
    /**
     * Activity模型对象
     * @var \app\admin\model\shopro\activity\Retailorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);
            
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if(isset($filter['date'])){
                $where = [];
                $rawdate = $filter['date'];
                $rawdate = str_replace(' - ', ',', $rawdate);
                $arr = array_slice(explode(',', $rawdate), 0, 2);

                $where['date'][] = ['gt',$arr[0]];
                $where['date'][] = ['lt',$arr[1]];
            }

            $list = db('report_order_day')
                ->fieldRaw("*")
                ->where($where)
                ->order($sort." ".$order)
                ->paginate($limit);

            $retdata = $list->items();

            $agentList = Agentstore::idAndNameLists();

            $typedarr = [
                'bargain' => '助力砍',
                'gift'    => '高级礼包',
                'groupon' => '抢购',
                'lgift'   => '小礼包',
                'ltravel' => '旅游路线',
                'normal'  => '普通商品',
                'travel'  => '旅游套餐',
                'seckill' => '秒杀',
            ];

            foreach ($retdata as &$item){
                $item['activity_type'] = isset($typedarr[$item['activity_type']]) ? $typedarr[$item['activity_type']] : $item['activity_type'];

                $item['agent_name'] = isset($agentList[$item['agent_id']]) ? $agentList[$item['agent_id']] : $item['agent_id'];

                $item['profit'] = round($item['price_cnt'] - $item['cost_cnt'] - $item['commission_cnt'],2);
            }

            $totaldata = $this->total($retdata);
            if(!empty($totaldata)){
                //不为空
                $retdata[] = $totaldata;
            }

            $result = array("total" => $list->total(), "rows" => $retdata);

            return json($result);
        }
        return $this->view->fetch();
    }

    protected function total($retdata)
    {
        //汇总
        $totaldata = [];
        if(!empty($retdata[0])){
            foreach ($retdata[0] as $k=>$v){
                if($k=='date'){
                    $totaldata[$k] = '汇总';
                }else{
                    $totaldata[$k] = 0;
                }
            }
        }

        foreach ($retdata as $item) {
            $totaldata['order_person_cnt'] = round($totaldata['order_person_cnt'] + $item['order_person_cnt'], 2);
            $totaldata['order_cnt'] = round($totaldata['order_cnt'] + $item['order_cnt'], 2);
            $totaldata['price_cnt'] = round($totaldata['price_cnt'] + $item['price_cnt'], 2);
            $totaldata['cost_cnt'] = round($totaldata['cost_cnt'] + $item['cost_cnt'], 2);
            $totaldata['commission_cnt'] = round($totaldata['commission_cnt'] + $item['commission_cnt'], 2);
            if (isset($totaldata['profit'])) {
                $totaldata['profit'] = round($totaldata['profit'] + $item['profit'], 2);
            } else {
                $totaldata['profit'] = $item['profit'];
            }
        }

        return $totaldata;
    }
}
